package com.ruoyi.business.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.ruoyi.business.domain.BankCard;
import com.ruoyi.business.domain.vo.BankCardVO;
import com.ruoyi.business.mapper.BankCardMapper;
import com.ruoyi.business.service.BankCardService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import org.springframework.stereotype.Service;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryChain;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.utils.StringUtils;

import java.time.LocalDateTime;
import java.util.Map;

import static com.ruoyi.business.domain.table.BankCardTableDef.BANK_CARD;


/**
 * 服务实现 : 银行卡
 *
 * @Author : ljq
 * @Created : 2025/10/5
 */
@Service
public class BankCardServiceImpl extends ServiceImpl<BankCardMapper, BankCard> implements BankCardService {

    @Override
    public Page<BankCardVO> listByCondition(BankCard entity, PageDomain domain) {
        QueryChain<BankCard> queryChain = QueryChain.of(this.getMapper())
                .select(BANK_CARD.DEFAULT_COLUMNS)
                .from(BANK_CARD).as("t1");
        this.baseCondition(queryChain, entity);
        return queryChain
                .withRelations()
                .pageAs(new Page<>(domain.getPageNum(), domain.getPageSize()), BankCardVO.class);
    }

    @Override
    public boolean save(BankCard entity) {
        entity.setCardBin(entity.getCardNumber().substring(0, 6));
        entity.setUserId(SecurityUtils.getUserId());

        // 密钥
        String secretKey = RandomUtil.randomStringUpper(16);
        String encrypt = SecureUtil.aes(secretKey.getBytes()).encryptBase64(entity.getCardNumber());
        entity.setCardNumberHash(secretKey);
        entity.setCardNumber(encrypt);

        return super.save(entity);
    }


    @Override
    public boolean updateById(BankCard entity) {
        entity.setCardBin(entity.getCardNumber().substring(0, 6));
        entity.setUserId(SecurityUtils.getUserId());

        // 密钥
        String secretKey = RandomUtil.randomStringUpper(16);
        String encrypt = SecureUtil.aes(secretKey.getBytes()).encryptBase64(entity.getCardNumber());
        entity.setCardNumberHash(secretKey);
        entity.setCardNumber(encrypt);

//        String decrypt = aes.decryptStr(encrypt);
//        Md5Utils.hash()
        return super.updateById(entity);
    }

    /* ------------------- 基础查询条件 --------------------- */
    private QueryChain baseCondition(QueryChain chain, BankCard entity) {
        // 银行卡号
        if (StringUtils.isNotEmpty(entity.getCardId())) {
            chain.where(BANK_CARD.CARD_ID.eq(entity.getCardId()));
        }
        // 用户ID
        if (StringUtils.isNotNull(entity.getUserId())) {
            chain.where(BANK_CARD.USER_ID.eq(entity.getUserId()));
        }
        // 卡号（加密存储）
        if (StringUtils.isNotEmpty(entity.getCardNumber())) {
            chain.where(BANK_CARD.CARD_NUMBER.eq(entity.getCardNumber()));
        }
        // 卡号哈希（用于查询）
        if (StringUtils.isNotEmpty(entity.getCardNumberHash())) {
            chain.where(BANK_CARD.CARD_NUMBER_HASH.eq(entity.getCardNumberHash()));
        }
        // 卡BIN号（前6位）
        if (StringUtils.isNotEmpty(entity.getCardBin())) {
            chain.where(BANK_CARD.CARD_BIN.eq(entity.getCardBin()));
        }
        // 卡类型：借记卡、信用卡、预付卡
        if (StringUtils.isNotEmpty(entity.getCardType())) {
            chain.where(BANK_CARD.CARD_TYPE.eq(entity.getCardType()));
        }
        // 银行卡片名称
        if (StringUtils.isNotEmpty(entity.getCardName())) {
            chain.where(BANK_CARD.CARD_NAME.eq(entity.getCardName()));
        }
        // 银行关联ID
        if (StringUtils.isNotNull(entity.getBankId())) {
            chain.where(BANK_CARD.BANK_ID.eq(entity.getBankId()));
        }
        // 币种
        if (StringUtils.isNotEmpty(entity.getCurrency())) {
            chain.where(BANK_CARD.CURRENCY.eq(entity.getCurrency()));
        }
        // CVV加密值
        if (StringUtils.isNotEmpty(entity.getCvvEncrypted())) {
            chain.where(BANK_CARD.CVV_ENCRYPTED.eq(entity.getCvvEncrypted()));
        }
        // 银行卡状态
        if (StringUtils.isNotEmpty(entity.getStatus())) {
            chain.where(BANK_CARD.STATUS.eq(entity.getStatus()));
        }

        Map<String, Object> params = entity.getParams();

        // 有效期
        String expiryDateRange = params.getOrDefault("expiryDateRange", "").toString();
        if (StringUtils.isNotEmpty(expiryDateRange)) {
            String[] split = expiryDateRange.split(",");
            chain.where(BANK_CARD.EXPIRY_DATE.between(split[0], split[1]));
        }

        // 创建时间
        String createTimeRange = params.getOrDefault("createTimeRange", "").toString();
        if (StringUtils.isNotEmpty(createTimeRange)) {
            String[] split = createTimeRange.split(",");
            chain.where(BANK_CARD.CREATE_TIME.between(split[0], split[1]));
        }

        // 更新时间
        String updateTimeRange = params.getOrDefault("updateTimeRange", "").toString();
        if (StringUtils.isNotEmpty(updateTimeRange)) {
            String[] split = updateTimeRange.split(",");
            chain.where(BANK_CARD.UPDATE_TIME.between(split[0], split[1]));
        }

        // 银行卡号-模糊左匹配
        String cardIdLikeLeft = params.getOrDefault("cardIdLikeLeft", "").toString();
        if (StringUtils.isNotEmpty(cardIdLikeLeft)) {
            chain.where(BANK_CARD.CARD_ID.likeLeft(cardIdLikeLeft));
        }

        // 卡号（加密存储）-模糊左匹配
        String cardNumberLikeLeft = params.getOrDefault("cardNumberLikeLeft", "").toString();
        if (StringUtils.isNotEmpty(cardNumberLikeLeft)) {
            chain.where(BANK_CARD.CARD_NUMBER.likeLeft(cardNumberLikeLeft));
        }

        // 卡号哈希（用于查询）-模糊左匹配
        String cardNumberHashLikeLeft = params.getOrDefault("cardNumberHashLikeLeft", "").toString();
        if (StringUtils.isNotEmpty(cardNumberHashLikeLeft)) {
            chain.where(BANK_CARD.CARD_NUMBER_HASH.likeLeft(cardNumberHashLikeLeft));
        }

        // 卡BIN号（前6位）-模糊左匹配
        String cardBinLikeLeft = params.getOrDefault("cardBinLikeLeft", "").toString();
        if (StringUtils.isNotEmpty(cardBinLikeLeft)) {
            chain.where(BANK_CARD.CARD_BIN.likeLeft(cardBinLikeLeft));
        }

        // 卡类型：借记卡、信用卡、预付卡-模糊左匹配
        String cardTypeLikeLeft = params.getOrDefault("cardTypeLikeLeft", "").toString();
        if (StringUtils.isNotEmpty(cardTypeLikeLeft)) {
            chain.where(BANK_CARD.CARD_TYPE.likeLeft(cardTypeLikeLeft));
        }

        // 卡片名称-模糊左匹配
        String cardNameLikeLeft = params.getOrDefault("cardNameLikeLeft", "").toString();
        if (StringUtils.isNotEmpty(cardNameLikeLeft)) {
            chain.where(BANK_CARD.CARD_NAME.likeLeft(cardNameLikeLeft));
        }

        // 币种-模糊左匹配
        String currencyLikeLeft = params.getOrDefault("currencyLikeLeft", "").toString();
        if (StringUtils.isNotEmpty(currencyLikeLeft)) {
            chain.where(BANK_CARD.CURRENCY.likeLeft(currencyLikeLeft));
        }

        // CVV加密值-模糊左匹配
        String cvvEncryptedLikeLeft = params.getOrDefault("cvvEncryptedLikeLeft", "").toString();
        if (StringUtils.isNotEmpty(cvvEncryptedLikeLeft)) {
            chain.where(BANK_CARD.CVV_ENCRYPTED.likeLeft(cvvEncryptedLikeLeft));
        }

        // 卡片状态-模糊左匹配
        String statusLikeLeft = params.getOrDefault("statusLikeLeft", "").toString();
        if (StringUtils.isNotEmpty(statusLikeLeft)) {
            chain.where(BANK_CARD.STATUS.likeLeft(statusLikeLeft));
        }

        // 创建者-模糊左匹配
        String createByLikeLeft = params.getOrDefault("createByLikeLeft", "").toString();
        if (StringUtils.isNotEmpty(createByLikeLeft)) {
            chain.where(BANK_CARD.CREATE_BY.likeLeft(createByLikeLeft));
        }

        // 更新者-模糊左匹配
        String updateByLikeLeft = params.getOrDefault("updateByLikeLeft", "").toString();
        if (StringUtils.isNotEmpty(updateByLikeLeft)) {
            chain.where(BANK_CARD.UPDATE_BY.likeLeft(updateByLikeLeft));
        }

        // 银行卡号-模糊匹配
        String cardIdLike = params.getOrDefault("cardIdLike", "").toString();
        if (StringUtils.isNotEmpty(cardIdLike)) {
            chain.where(BANK_CARD.CARD_ID.like(cardIdLike));
        }

        // 卡号（加密存储）-模糊匹配
        String cardNumberLike = params.getOrDefault("cardNumberLike", "").toString();
        if (StringUtils.isNotEmpty(cardNumberLike)) {
            chain.where(BANK_CARD.CARD_NUMBER.like(cardNumberLike));
        }

        // 卡号哈希（用于查询）-模糊匹配
        String cardNumberHashLike = params.getOrDefault("cardNumberHashLike", "").toString();
        if (StringUtils.isNotEmpty(cardNumberHashLike)) {
            chain.where(BANK_CARD.CARD_NUMBER_HASH.like(cardNumberHashLike));
        }

        // 卡BIN号（前6位）-模糊匹配
        String cardBinLike = params.getOrDefault("cardBinLike", "").toString();
        if (StringUtils.isNotEmpty(cardBinLike)) {
            chain.where(BANK_CARD.CARD_BIN.like(cardBinLike));
        }

        // 卡类型：借记卡、信用卡、预付卡-模糊匹配
        String cardTypeLike = params.getOrDefault("cardTypeLike", "").toString();
        if (StringUtils.isNotEmpty(cardTypeLike)) {
            chain.where(BANK_CARD.CARD_TYPE.like(cardTypeLike));
        }

        // 卡片名称-模糊匹配
        String cardNameLike = params.getOrDefault("cardNameLike", "").toString();
        if (StringUtils.isNotEmpty(cardNameLike)) {
            chain.where(BANK_CARD.CARD_NAME.like(cardNameLike));
        }

        // 币种-模糊匹配
        String currencyLike = params.getOrDefault("currencyLike", "").toString();
        if (StringUtils.isNotEmpty(currencyLike)) {
            chain.where(BANK_CARD.CURRENCY.like(currencyLike));
        }

        // CVV加密值-模糊匹配
        String cvvEncryptedLike = params.getOrDefault("cvvEncryptedLike", "").toString();
        if (StringUtils.isNotEmpty(cvvEncryptedLike)) {
            chain.where(BANK_CARD.CVV_ENCRYPTED.like(cvvEncryptedLike));
        }

        // 卡片状态-模糊匹配
        String statusLike = params.getOrDefault("statusLike", "").toString();
        if (StringUtils.isNotEmpty(statusLike)) {
            chain.where(BANK_CARD.STATUS.like(statusLike));
        }

        // 创建者-模糊匹配
        String createByLike = params.getOrDefault("createByLike", "").toString();
        if (StringUtils.isNotEmpty(createByLike)) {
            chain.where(BANK_CARD.CREATE_BY.like(createByLike));
        }

        // 更新者-模糊匹配
        String updateByLike = params.getOrDefault("updateByLike", "").toString();
        if (StringUtils.isNotEmpty(updateByLike)) {
            chain.where(BANK_CARD.UPDATE_BY.like(updateByLike));
        }


        return chain;
    }
}